#include "stdafx.h"
#include "jtfBaseState.h"
#include "jtf.h"

CJtfBaseState::CJtfBaseState(BSTR executable, BSTR commandLine, BSTR mainWindowLocator, BSTR techDomains) : 
jstrExecutable(executable), jstrCommandLineOrUrl(commandLine), jstrMainWindow(mainWindowLocator)
{
  this->jobjBrowserBaseState = 0;
  this->jobjBaseState = 0;
  // parse techdomains into a std::set
  std::set<std::wstring> techDomainSet;
  size_t techDomainsLen = SysStringLen(techDomains);
  wchar_t* tmpTechDomains = new wchar_t[techDomainsLen + 1];
  wcsncpy_s(tmpTechDomains, techDomainsLen + 1, techDomains, techDomainsLen);
  tmpTechDomains[techDomainsLen] = 0;
  wchar_t* pos = tmpTechDomains + techDomainsLen;
  while (pos >= tmpTechDomains)
  {
    if (*pos == L';' || *pos == L' ')
    {
      *pos = 0;
      if (pos[1] != 0)
        techDomainSet.insert(std::wstring(pos+1));
    }
    pos--;
  }
  if (pos[1] != 0)
    techDomainSet.insert(std::wstring(pos+1));
  delete tmpTechDomains;
  // create jni array from std::set
  JtfTechDomainClass jtfTechDomain;
  jarrTechDomains = jni.Env()->NewObjectArray(techDomainSet.size(), jtfTechDomain.Class(), NULL);
  jni.Env()->NewGlobalRef(jarrTechDomains);
  jsize i = 0;
  for (std::set<std::wstring>::iterator it = techDomainSet.begin(); it != techDomainSet.end(); ++it)
  {
    CJniString jshlp(*it);
    CJniLocalReference<jobject> jobjTechDomain = jtfTechDomain.Constructor.New(VARGS, jshlp.JString());
    jni.Env()->SetObjectArrayElement(jarrTechDomains, i++, jobjTechDomain.Get());
  }
}

CJtfBaseState::~CJtfBaseState()
{
  jni.Env()->DeleteGlobalRef(jarrTechDomains);
  if (jobjBrowserBaseState)
    jni.Env()->DeleteGlobalRef(jobjBrowserBaseState);
  if (jobjBaseState)
    jni.Env()->DeleteGlobalRef(jobjBaseState);
}

jobject CJtfBaseState::GetBaseState()
{
  if (!jobjBaseState)
  {
    JtfBaseStateClass jtfBaseState;
    jobjBaseState = jtfBaseState.Constructor.New(VARGS, GetExecutable(), GetCommandLine(), GetMainWindowLocator(), jarrTechDomains);
    jni.Env()->NewGlobalRef(jobjBaseState);
  }
  return jobjBaseState;
}

jobject CJtfBaseState::GetBrowserBaseState()
{
  if (!jobjBrowserBaseState)
  {
    JtfBrowserBaseStateClass jtfBrowserBaseState;
    jobjBrowserBaseState = jtfBrowserBaseState.Constructor.New(VARGS, GetExecutable(), GetUrl(), GetMainWindowLocator(), jarrTechDomains);
    jni.Env()->NewGlobalRef(jobjBrowserBaseState);
  }
  return jobjBrowserBaseState;
}
